/* 
 *  Copyright 2012 CodeMagi, Inc.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.codemagi.taglibs.taxonomy;

import com.codemagi.servlets.model.*;
import com.codemagi.util.*;
import java.util.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

/**
 * This class implements the &lt;tax:menu&gt; tag, which presents a list of Nodes associated with a Term
 *
 *  @version 1.0
 *  @author August Detlefsen for CodeMagi, Inc.
 */
public class TaxonomyMenu extends TaxonomyTag {

    String context   = null;
    boolean link     = true;

    //SETTERS --------------------------------------------

    public void setContext(String newValue) {
	context = newValue;
    }

    public void setLink(boolean newValue) {
	link = newValue;
    }

    public void setLink(Boolean newValue) {
	if (newValue != null) link = newValue.booleanValue();
    }

    public void setLink(String newValue) {
	link = Boolean.valueOf(newValue);
    }

    public int doStartTag() throws JspException {

	//get the term based on the alias
	Term term = controller.getTerm(alias);

	//get the matches for this term
	List<Node> matches = controller.getMatches(term);

        try {
            // get what we need from the page                                       
            HttpServletRequest req = (HttpServletRequest)pageContext.getRequest();
            JspWriter out = pageContext.getOut();

	    //What context should we link to? 
	    if (Utils.isEmpty(context)) context = req.getContextPath();

	    //print the start tag
	    out.print("<ul id=\"" + term.getAlias() + "\"");
            if (!Utils.isEmpty(markupClass)) out.print(" class=\"" + markupClass + "\"");
	    
	    // include any attributes we've got here                               
	    printAttributes(out, attributes);
	    
            out.print(">");
	    
            /*                                                                                                  
             * Print out our nodes.             
             */
	    for (Node node : matches) {

		out.print("<li>");

		if (link) {
		    out.print("<a href=\"" + context + "/node/" + node.getId() + "\">");
		}

		out.print( node.getName() );

		if (link) out.print("</a>");

		out.print("</li>");
	    }

        } catch (Exception ex) {
            log.debug("", ex);
            throw new JspTagException(ex.getMessage());
        }

        return SKIP_BODY;
    }

}
